package com.java.comminution.exer1;

/**
 * 生产者与消费者的线程通信问题
 *
 * @author luzhikun
 * @date &{DATE}-21:46
 */
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Product product = new Product(clerk);
        Thread thread = new Thread(product);
        thread.setName("生产者");
        thread.start();

        Consumert consumer = new Consumert(clerk);
        Thread thread1 = new Thread(consumer);
        thread1.setName("消费者");
        thread1.start();
    }
}

class Product implements Runnable {
    private Clerk clerk;

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.productMethod();
        }
    }
}

class Consumert implements Runnable {
    private Clerk clerk;

    public Consumert(Clerk clerk1) {
        this.clerk = clerk1;
    }

    @Override
    public void run() {
        while (true) {
            clerk.consunmerMethod();
        }
    }
}


class Clerk {
    private static int productNumber = 0;

    public synchronized void consunmerMethod() {
        if (productNumber > 0) {
            System.out.println(Thread.currentThread().getName() + "开始消费第：" + productNumber + "个产品");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            productNumber--;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void productMethod() {
        if (productNumber < 20) {
            productNumber++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "开始生产第：" + productNumber + "个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
